<template>
  <el-form :model="form" ref="ruleFormRef" :label-position="labelPosition" label-width="100px" :inline="true"
    :rules="rules" status-icon class="demo-form-inline">
    <el-form-item label="工法名称" prop="constructionName">
      <el-input v-model="form.constructionName" maxlength="50" placeholder="请输入" clearable :disabled="1"/>
    </el-form-item>

    <el-form-item label="工法编号" prop="constructionNumber">
      <el-input v-model="form.constructionNumber" maxlength="19" placeholder="请输入" clearable :disabled="1" />
    </el-form-item>

    <!-- prop="contractUnit" -->
    <el-form-item label="联系单位" prop="contractUnitId">

      <popup-tree-input :data="data.contractUnitOption" :props="data.popupTreeProps" :prop="deptForm.parentName == null
          ? $t('message.org.top_menu')
          : form.contractUnit
        " :node-key="'' + deptForm.parentId" :current-change-handle="changeValue" :disabled="1" />

    </el-form-item>
    <el-form-item label="联系人" prop="contract">
      <!-- <SelectOption :options="data.contractOption" :selectValue="form.contract" @change-value="changeValue1">
      </SelectOption> -->
      <user-list-modal v-model="form.contract" @update:modelValue="changeValue1" :default-users="[]" :multiple="false"
        :devType="'platform'" :disabled="1" />
    </el-form-item>
    <el-form-item label="工法级别" prop="trdLevel">
      <SelectOption :selectValue="form.trdLevel" :options="data.levelMethod" @change-value="changeValue2" :disabled="1">
      </SelectOption>
    </el-form-item>
    <el-form-item label="工法类别" prop="trdClass">
      <SelectOption :selectValue="form.trdClass" :options="data.methodType" @change-value="changeValue3" :disabled="1">
      </SelectOption>
    </el-form-item>
    <el-form-item label="企业排名" prop="enterpriseRanking">
      <SelectOption :selectValue="form.enterpriseRanking" :options="data.enterpriseRankingOptions"
        @change-value="changeValue4" :disabled="1">
      </SelectOption>
    </el-form-item>
    <el-form-item label="参加情况" prop="editCondition">
      <SelectOption :selectValue="form.editCondition" :options="data.editConditionOption" @change-value="changeValue5" :disabled="1">
      </SelectOption>
    </el-form-item>
    <el-form-item label="发布单位" prop="publicUnit">
      <el-input v-model="form.publicUnit" maxlength="50" placeholder="请输入" clearable :disabled="1" />
    </el-form-item>
    <el-form-item label="发布时间" prop="publicDate">
      <el-date-picker v-model="form.publicDate" format="YYYY-MM-DD" type="date" placeholder="选择日期" clearable :disabled="1"
        @change="handleChangeDate" />
    </el-form-item>
    <el-form-item label="主题词" prop="themeWord">
      <el-input v-model="form.themeWord" placeholder="请输入" clearable  :disabled="1"/>
    </el-form-item>
    <el-form-item label="主要完成人" prop="mainCompletePersons">
      <user-list-modal v-model="form.mainCompletePersons" @update:modelValue="handleProjectLeader"
        :default-users="selectArr" :multiple="true" :devType="'platform'" :disabled="1" />
    </el-form-item>
    <el-form-item label="完成单位" style="width: 100%" prop="projectHeadUnitIds">
      <div class="selectLabel">
        <div>
          <el-tag v-for="tag in data.unit" :key="tag" class="mx-1" closable  :disabled="1" >
<!--          <el-tag v-for="tag in data.unit" :key="tag" class="mx-1" closable @close="handleClose(tag)">-->
            {{ tag.value }}
          </el-tag>
        </div>
      </div>
<!--      <span class="addLabel" @click="addUnitBox">添加单位</span>-->
    </el-form-item>
    <el-form-item style="width: 97%" label="工法内容简介" prop="trdContentIntroduce">
      <el-input v-model="form.trdContentIntroduce" :autosize="{ minRows: 2 }" maxlength="1000" type="textarea"
        placeholder="请输入"  :disabled="1" />
    </el-form-item>
    <el-form-item label="备注" class="labelHeight" style="width: 97%">
      <el-input v-model="form.remark" :autosize="{ minRows: 3 }" maxlength="1000" type="textarea" placeholder="请输入"  :disabled="1"/>
    </el-form-item>
  </el-form>

  <!-- 弹窗 -->
  <el-dialog v-model="data.addUnit" append-to-body width="50%" top="10vh" :show-close="false"
    :close-on-click-modal="false">
    <template #title>
      <el-tabs v-model="data.activeName" class="demo-tabs">
        <el-tab-pane label="选择单位" name="first">
          <div>
            <el-row>
              <el-col :span="24">
                <p>内部单位：</p>
                <el-cascader-panel :options="data.selOp" v-model="innerValue"
                  :props="{ emitPath: false, value: 'id', label: 'name' }" :show-all-levels="false"
                  @change="innerValueChange" />
              </el-col>
              <el-col :span="24" style="margin-top: 15px">
                <span>外部单位：</span>
                <el-input v-model="data.outsideValue" style="width: 200px; margin-right: 15px" />
                <el-button type="primary" @click="addOutside()">添加</el-button>
              </el-col>
            </el-row>
            <div class="unitBox">
              <div class="title">已选单位</div>
              <div class="tagBox">
                <el-tag v-for="tag in data.unit" :key="tag" class="mx-1" closable @close="handleClose(tag)">
                  {{ tag.value }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.addUnit = false">关闭</el-button>
        <el-button type="primary" @click="save()">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts">
import * as proxy from '@/constants/proxy'
import request from '@/utils/request'
import UserListModal from '@/views/project/components/UserListModal/index.vue'
import { getUserList } from '@/views/science/api/common'
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import Table from '@/views/science/components/table/table.vue'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'
import tableData from './tableHeader.json'

export default {
  components: {
    SelectOption, Table, UserListModal,PopupTreeInput
  },
  emits: {
    valueFlag: null,
  },
  props: {
    selectArr: {
      type: Array,
      required: true,
    },
    addFlag: {
      type: Number,
      required: true,
    },
  },

  setup(props, { emit }) {
    const deptForm = {
            parentId: 0,
            parentName: '',
        }

    const store = useStore()
    const labelPosition = ref('right')

    const data = reactive({
      popupTreeProps: {
                label: 'name',
                children: 'children',
            },
      unit: [] as any,
      completeUnits: '',
      activeName: ref('first'),
      addUnit: false,
      addPerson: false,
      innerValue: '',
      outsideValue: '',
      contractUnitOption: [],
      levelMethod: [],
      methodType: [],
      enterpriseRankingOptions: [],
      editConditionOption: [],

      orgAllList: [],
      levelOptions: [],
      currentStage: [],
      business: [],
      editCondition: [],

      contractOption: [],
      trdLevelOption: [],
      trdClassOption: [],
      //添加人员
      params: {
        current: 1,
        size: 10,
        name: "",
        unitOrg: ""
      },
      unitList: [],
      userList: [],
      columns: tableData.userList,
      page: { page: 1, limit: 10, total: 0 },
      ids: [],
      selOp:[],
    })

    // 字典
    const affiliation = () => {
      request({
        url: proxy.CHECC_API_CMS + '/dictItem/codelist',
        method: 'post',
        data: [
          'KJSL_CONSTRUCTION_METHOD_LEVEL_CATEGORY',
          'KJSL_ENTERPRISE_RANKING',
          'KJSL_STANDARD_LEVEL_CATEGORY',
          'KJSL_PREPARATION_CATEGORY',
          'KJSL_AT_PRESENT_STAGE',
          'KJSL_PARTICIPATION_STATUS1',
          'KJSL_BUSINESS_SECTOR',
          'KJSL_STANDARD_LEVEL_CATEGORY',
        ],
      }).then((res) => {
        data.levelMethod = res.data.data.KJSL_CONSTRUCTION_METHOD_LEVEL_CATEGORY
        // 企业排名
        data.enterpriseRankingOptions = res.data.data.KJSL_ENTERPRISE_RANKING

        // 参加情况
        data.editConditionOption = res.data.data.KJSL_PARTICIPATION_STATUS1

        data.orgAllList = res.data.data.KJSL_STANDARD_LEVEL_CATEGORY
        data.levelOptions = res.data.data.KJSL_PREPARATION_CATEGORY
        data.currentStage = res.data.data.KJSL_AT_PRESENT_STAGE
        data.business = res.data.data.KJSL_BUSINESS_SECTOR
        data.editCondition = res.data.data.KJSL_PARTICIPATION_STATUS1
      })
    }
    const form = reactive(store.state.technicalNorms.methodForm)
    watch(() => form.completeUnitIds, () => {
      let str = form.completeUnits
      let arr1 = str ? str.split(",") : [];
      let arr2 = form.completeUnitIds ? form.completeUnitIds.split(",") : [];

      data.unit = arr1.map((id: string, index: number) => ({
        value: arr1[index],
        id:arr2[index]
      }))
      // data.unit = arr;
      console.log('unit',data.unit);
    })

    // console.log('form',form,'----',form.completeUnitIds);

    // if (form.completeUnitIds) {
    //   let arr1 = form.completeUnits.split(",");
    //   let arr2 = form.completeUnitIds.split(",");

    //   let dataObj: Record<string, any> = {};

    //   arr2.map((item: any, index: number) => {
    //     dataObj[item] = arr1[index];
    //   });

    //   let arr: { value: any; id: string }[] = [];
    //   for (let key in dataObj) {
    //     arr.push({
    //       value: dataObj[key],
    //       id: key
    //     });
    //   }
    //   data.unit = arr;
    //   console.log('unit',arr);
    // }
    // const value1 = ref('')

    const getUser = () => {
      request({
        url: proxy.CHECC_API_CMS + '/user/getAll',
        method: 'get',
      }).then((res) => {
        data.contractOption = res.data.data
      })
    }

    const getUnit = () => {
      request({
        url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
        method: 'get',
      }).then((res) => {
        data.contractUnitOption = res.data.data
        data.selOp = res.data.data
      })
    }

    watch(form, (newValue, oldValue) => {
      store.commit('technicalNorms/getMethodForm', { ...form })
    })

    // 联系单位
    const changeValue = (item) => {
      form.contractUnit = item.name
      form.contractUnitId = item.id
    }
    const changeValue1 = (item) => {
      form.contract = item.cname
      form.contractId = item.userId

    }

    //  工法级别
    const changeValue2 = (item) => {
      form.trdLevel = item.itemText
      form.trdLevelId = item.itemValue

      if (item.children != null) {
        data.methodType = item.children

        form.trdClass = ''
        form.trdClassId = ''
      }
    }

    // 工法类别

    const changeValue3 = (item) => {
      form.trdClass = item.itemText
      form.trdClassId = item.itemValue
    }

    // 企业排名

    const changeValue4 = (item) => {
      form.enterpriseRanking = item.itemText

      form.enterpriseRankingId = item.itemValue
    }

    // 参加情况

    const changeValue5 = (item) => {
      form.editCondition = item.itemText

      form.editConditionId = item.itemValue
    }

    //选择人员的回调
    const handleProjectLeader = (ids, names) => {
      console.log('选择人员的回调',ids);
      form.mainCompletePersonIds = ids
      form.mainCompletePersons = names
    }

    const rules = reactive({
      constructionName: [{ required: true, message: '请输入工法名称', trigger: 'blur' }],
      constructionNumber: [{ required: true, message: '请输入工法编号', trigger: 'blur' }],
      contractUnitId: [{ required: true, message: '请选择联系单位', trigger: 'change' }],
      contract: [{ required: true, message: '请选择联系人', trigger: ['change', 'blur'] }],
      trdLevel: [{ required: true, message: '请选择工法级别', trigger: 'change' }],
      trdClass: [{ required: true, message: '请选择工法类别', trigger: 'change' }],
      enterpriseRanking: [{ required: true, message: '请选择企业排名', trigger: 'change' }],
      editCondition: [{ required: true, message: '请选择参加情况', trigger: 'change' }],
      publicUnit: [{ required: true, message: '请输入发布单位', trigger: 'blur' }],
      publicDate: [{ required: true, message: '请选择发布时间', trigger: 'change' }],
      themeWord: [{ required: true, message: '请输入主题词', trigger: 'blur' }],
      completeUnits: [{ required: false, message: '请输入完成单位', trigger: 'blur' }],
      mainCompletePersonIds: [{ required: true, message: '请输入主要完成人', trigger: 'blur' }],
      mainCompletePersons: [{ required: true, message: '请输入主要完成人', trigger: 'blur' }],
      trdContentIntroduce: [{ required: true, message: '请输入工法简介', trigger: 'blur' }],
    })

    //次级连选
    const props1 = {
      checkStrictly: true,
      value: 'id',
      label: 'name',
    }

    const ruleFormRef = ref()
    const submitForm = async () => {
      await ruleFormRef.value.validate((valid) => {
        if (valid) {
          emit('valueFlag', true)
          console.log('submit!')
        } else {
          emit('valueFlag', false)
        }
      })
    }


    let unit: any = ref([])

    // let personUnit: any = ref([])

    const handleSave = () => {
      const form = store.state.technologyStrength.technologyProjectsInfo

      console.log(form)
    }

    const getTreeData = (data) => {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children !== undefined) {
          if (data[i].children.length < 1) {
            // children若为空数组，则将children设为undefined
            data[i].children = undefined
          } else {
            // children若不为空数组，则继续 递归调用 本方法
            getTreeData(data[i].children)
          }
        }
      }
      return data
    }

    const save = () => {
      let ids = data.unit.map((item) => item.id);
      let names = data.unit.map((item) => item.value);

      let filterArr = ids.filter(function (i) {
        return i && i.trim();
      });
      form.completeUnitIds = filterArr.join(",");
      form.completeUnits = names.join(",");

      data.addUnit = false;

    }

    const findItemNested = (arr, itemId, nestingKey) =>
      arr.reduce((a, item) => {
        if (a) return a
        if (item.id === itemId) return item
        if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
      }, null)

    const addUnitBox = () => {
      data.addUnit = true
    }
    //-------------------------------添加人员

    // 弹窗中下拉选择
    const options = reactive({
      unitList: computed(() => store.state.technologyStrength.orgAllList),
      userAllList: computed(() => store.state.technologyStrength.userAllList),
    })
    //分页获取人员列表
    const getUseList = async () => {
      const res = await getUserList(data.params)
      data.userList = res.data.data.records
      data.page.total = res.data.data.total
    }
    const delectIds = (ids) => {
      data.ids = ids
    }
    const person: any = ref([])
    const selectItemFn = (item) => {
      item.filter(
        (item, index) => {
          const obj = {
            username: item.cname,
            userId: item.userId
          }
          if (JSON.stringify(person.value).indexOf(JSON.stringify(obj)) == -1) person.value.push(obj);
        }
      )
    }


    const changeValueUnit = (item) => {
      data.params.unitOrg = item.id
    }


    const handleUnitString = (data, item) => {
      if (data) {
        let arr = data.split(',')
        var index = arr.indexOf(item)
        if (!(index > -1)) {
          // 代表不存在，
          arr.push(item)
        } else {
          arr.splice(index, 1)
        }
        return arr.join(',')
      } else {
        let arr: any = []
        arr.push(item)
        return arr.join(',')
      }
    }

    const innerValue = ref()

    const innerValueChange = (value) => {
      const item = findItemNested(data.selOp, value, "children");
      data.unit.push({
        id: item.id,
        value: item.name,
      });

    }

    const addOutside = () => {
      if (data.outsideValue) {
        data.unit.push({
          id: '',
          value: data.outsideValue,
        })
      }

      data.outsideValue = ''
    }


    const handleClose = (tag) => {
      data.unit.splice(data.unit.indexOf(tag), 1);

      let ids = data.unit.map((item) => item.id);
      let names = data.unit.map((item) => item.value);

      let filterArr = ids.filter(function (i) {
        return i && i.trim();
      });

      form.completeUnitIds = filterArr.join(",");
      form.completeUnits = names.join(",");
    }

    const handleChangeDate = (val) => {
      const year = val.getFullYear() // 获取年份
      const month = val.getMonth() + 1 < 10 ? '0' + (val.getMonth() + 1) : val.getMonth() + 1 // 获取月份，需要加1
      const day = val.getDate() < 10 ? '0' + val.getDate() : val.getDate() // 获取日期
      const formattedDate = `${year}-${month}-${day}`

      form.publicDate = formattedDate
      store.commit('technologyStrength/getForm', { ...form })
    }

    onMounted(() => {
      // 数据字典
      affiliation()
      // 获取联系人
      getUser()
      // 获取联系单位
      getUnit()

      // 获取
    })

    return {
      labelPosition,
      props1,
      data,
      form,
      unit,
      innerValue,
      rules,
      submitForm,
      ruleFormRef,
      deptForm,
      handleProjectLeader,

      handleChangeDate,

      changeValue,
      changeValue1,
      changeValue2,
      changeValue3,
      changeValue4,
      changeValue5,
      addUnitBox,
      addOutside,
      handleClose,
      innerValueChange,
      save,
      handleSave,
      affiliation,
      changeValueUnit,
      options,
      delectIds,
      selectItemFn,

    }
  }
}
</script>
<style lang="scss" scoped>
.demo-form-inline .el-form-item {
  width: 48%;
}

:deep(.labelHeight .el-form-item__label) {
  line-height: 20px;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-date-editor.el-input__inner) {
  width: 100%;
}

:deep(.demo-form-inline .el-select) {
  width: 100%;
  margin: 0;
}

.el-select {
  width: 100%;
  margin: 0;
}

.selectLabel {
  width: 70%;
  min-height: 40px;
  line-height: 40px;
  padding: 0 15px;
  border: 1px solid #ccc;
  border-radius: 6px;
  display: inline-block;
  cursor: pointer;

}

.addLabel {
  display: inline-block;
  width: 120px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: #169bd5;
  border-radius: 6px;
  color: #fff;
  margin-left: 15px;
  margin-top: 6px;
  vertical-align: top;
  cursor: pointer;
}

.unitBox {
  width: 100%;
  margin: 30px 0;

  .title {
    padding: 15px 0;
    border-bottom: 1px solid #ccc;
  }

  .tagBox {
    line-height: 40px;
    margin-top: 15px;
    border: 1px solid #ccc;
    border-radius: 8px;
    padding: 10px 15px;
  }
}

.el-tag {
  margin-right: 10px;
}

.search-box {
  display: flex;
  justify-content: end;
  align-items: center;
  margin-bottom: 10px;
}
</style>
